<?php

namespace Acme\UserBundle\Controller;

use Symfony\Component\HttpFoundation\Session;

use Acme\MailerBundle\MailManager;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

use Acme\CommonBundle\AcmeCommonBundle;

use Acme\UserBundle\Entity\CmUser;
use Acme\UserBundle\Entity\CmUserInfo;
use Acme\CommonBundle\Entity\ConstUniversity;

use Acme\UserBundle\Form\UserInfoType;

use Symfony\Component\Security\Acl\Domain\UserSecurityIdentity;

class RegistController extends Controller
{	
    /**
     * @Route("/regist/{category_name}", defaults={"category_name" = "student"}, requirements={"category_name" = "student|teacher|outsider"}, name="AcmeUserBundle_RegistIndex")
     * @Template()
     */
    public function indexAction($category_name) {
    	$request = $this->get('request');
    	
    	$userInfo = new CmUserInfo();  // The form should be created by Owning Side
    	
    	$buildOption['category_name'] = $category_name;
    	$buildOption['build_for'] = 'regist';
    	$form = $this->createForm(new UserInfoType(), $userInfo, $buildOption);
    	
    	if ($request->getMethod() == 'POST') {
    		$form->bindRequest($request);
    		
    		if ($form->isValid()) {
    			$user = new CmUser();
    			$user = $userInfo->getUser();
    			
    			// load encoderfactory and set salt encoded password for user
    			$factory = $this->get('security.encoder_factory');
    			$encoder = $factory->getEncoder($user);
    			$password = $encoder->encodePassword($user->getPassword(), $user->getSalt());
    			$user->setPassword($password);
    			
    			// set user category
    			$category = array_search($category_name, $this->container->getParameter('userCategoryEn'));
    			$user->setCategory($category);
    			
    			if ($category_name != 'outsider') {
	    			// set user's university info
	    			$universityInfo = $userInfo->getUniversity();
	    			$userInfo->setUniversityInfo($universityInfo);
    			}
    			
    			// perform some action, such as save the object to the database
    			$em = $this->getDoctrine()->getEntityManager();
    			 
    			$em->persist($user);
    			
    			if ($category_name != 'outsider') {
    				$em->persist($userInfo); //固定实体
    			}
    			    			
    			// 传入数据库
    			$em->flush();
    			$this->get('session')->setFlash('notice', '恭喜您，注册成功!!');
    			
    			$this->get('mail_manager')->emailValid($user);
    			//return new RedirectResponse($this->generateUrl('AcmeUserBundle_RegistIndex'));
    		}
    	}
    	
    	return array('form' => $form->createView(), 'category_name' => $category_name);
    }
}
